﻿using System;
using EmbeddedSharp.Core;
using EmbeddedSharp.Scripting.Function;

namespace EmbeddedSharp.Scripting {
    public class ContextUserDefinedFunctionNode : UserDefinedFunctionNode {

        public IContext Context {
            get;
            set;
        }

        public override object Evaluate() {
            double[] parameterValue = new double[this.Parameters.Count];

            for(int index = 0; index < this.Parameters.Count; index++) {
                parameterValue[index] 
                    = Convert.ToDouble(this.Parameters[index].Evaluate());
            }

            string expr = base.FuncBody;
            for (int index = 0; index < this.Arguments.Length; index++)
            {
                expr = EmbeddedSharp.Core.Utils.ReplaceString(
                    this.Arguments[index], 
                    parameterValue[index].ToString(), 
                    expr);
            }

            Node root = ((ScriptingContext)Context).Parse(expr);
            object result = root.Evaluate();

            return result;
        }

        public override object Accept(IVisitor visitor) {
            return visitor.Visit(this);
        }
    }
}
